/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package LDAPAPI;

import LDAPAPI.Exceptions.LDAPConnectionException;
import org.forgerock.opendj.ldap.Connection;
import org.forgerock.opendj.ldap.ConnectionFactory;
import org.forgerock.opendj.ldap.Connections;
import org.forgerock.opendj.ldap.ErrorResultException;
import org.forgerock.opendj.ldap.LDAPConnectionFactory;
import org.forgerock.opendj.ldap.requests.Requests;

/**
 *
 * @author anvil
 */
public class AnvilConnection {
    protected String host;
    protected int port;
    protected String password;
    
    private ConnectionFactory factory = null;
    protected Connection connection = null;
    
    public AnvilConnection() {
        
    }
    
    public void connect(String url, int port, String adminDN, char[] adminPwd) throws LDAPConnectionException {
        try {
            this.factory = Connections.newAuthenticatedConnectionFactory(Connections.newHeartBeatConnectionFactory(new LDAPConnectionFactory(url, port)), Requests.newSimpleBindRequest(adminDN, adminPwd));
        } catch (Exception e) {
            disconnect();
            throw new LDAPConnectionException();
        }
    }

    protected void bind() throws ErrorResultException {
        this.connection = this.factory.getConnection();
    }

    protected void unbind() {
        if (this.connection != null) {
            this.connection.close();
        }
        this.connection = null;
    }

    public void disconnect() {
        if (this.factory != null) {
            this.factory.close();
        }
        this.factory = null;
    }

    public boolean isConnected() {
        return factory != null;
    }

    public boolean isBound() {
        return connection != null;
    }
}
